package xju.rjxy.shop.service.impl;

import xju.rjxy.shop.constant.BaseConstant;
import xju.rjxy.shop.mapper.GameMapper;
import xju.rjxy.shop.mapper.impl.GameMapperImpl;
import xju.rjxy.shop.model.domain.Game;
import xju.rjxy.shop.model.vo.GameVO;
import xju.rjxy.shop.model.vo.HomePageVO;
import xju.rjxy.shop.service.IGameService;

import java.util.List;

/**
 * 游戏服务接口实现类
 */
public class GameServiceImpl implements IGameService {
    private final GameMapper gameMapper = new GameMapperImpl();

    /**
     * 获取游戏列表
     */
    @Override
    public List<GameVO> getGameList() {
        System.out.println("[DEBUG] GameServiceImpl.getGameList - 开始获取游戏列表");
        try {
            System.out.println("[DEBUG] GameServiceImpl.getGameList - 调用gameMapper.selectGameList()");
            List<GameVO> gameList = gameMapper.selectGameList();
            System.out.println("[DEBUG] GameServiceImpl.getGameList - 从数据库获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            processGameList(gameList);
            System.out.println("[DEBUG] GameServiceImpl.getGameList - 返回游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            return gameList;
        } catch (Exception e) {
            System.err.println("[ERROR] GameServiceImpl.getGameList - 获取游戏列表失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 获取首页数据
     */
    @Override
    public HomePageVO getHomePageData(Integer userId) {
        System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 开始获取首页数据，userId: " + userId);
        try {
            HomePageVO homePageVO = new HomePageVO();
            
            // 获取热卖游戏（前10个）
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 开始获取热卖游戏");
            List<GameVO> hotGames = gameMapper.selectHotGames(10);
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 获取到热卖游戏，数量: " + (hotGames != null ? hotGames.size() : 0));
            // processGameList(hotGames);
            homePageVO.setHotGames(hotGames);
            
            // 获取推荐游戏（前8个）
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 开始获取推荐游戏");
            List<GameVO> recommendedGames = gameMapper.selectRecommendedGames(userId, 8);
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 获取到推荐游戏，数量: " + (recommendedGames != null ? recommendedGames.size() : 0));
            // processGameList(recommendedGames);
            homePageVO.setRecommendedGames(recommendedGames);
            
            // 获取打折游戏（前6个）
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 开始获取打折游戏");
            List<GameVO> discountGames = gameMapper.selectDiscountGames(6);
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 获取到打折游戏，数量: " + (discountGames != null ? discountGames.size() : 0));
            // processGameList(discountGames);
            homePageVO.setDiscountGames(discountGames);
            
            // 获取商城游戏（前20个）
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 开始获取商城游戏");
            List<GameVO> storeGames = gameMapper.selectBySalesOrder(0, 20);
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 获取到商城游戏，数量: " + (storeGames != null ? storeGames.size() : 0));
            // processGameList(storeGames);
            homePageVO.setStoreGames(storeGames);
            
            System.out.println("[DEBUG] GameServiceImpl.getHomePageData - 首页数据获取完成");
            return homePageVO;
        } catch (Exception e) {
            System.err.println("[ERROR] GameServiceImpl.getHomePageData - 获取首页数据失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 根据ID获取游戏详情
     */
    @Override
    public Game getGameById(Integer id) {
        System.out.println("[DEBUG] GameServiceImpl.getGameById - 开始根据ID获取游戏详情，id: " + id);
        try {
            if (id == null) {
                System.err.println("[ERROR] GameServiceImpl.getGameById - 游戏ID不能为空");
                throw new RuntimeException("游戏ID不能为空");
            }
            
            System.out.println("[DEBUG] GameServiceImpl.getGameById - 调用gameMapper.selectById()");
            Game game = gameMapper.selectById(id);
            System.out.println("[DEBUG] GameServiceImpl.getGameById - 获取到游戏详情: " + (game != null ? "成功" : "失败"));
            
            return game;
        } catch (Exception e) {
            System.err.println("[ERROR] GameServiceImpl.getGameById - 根据ID获取游戏详情失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 根据类别获取游戏列表
     */
    @Override
    public List<GameVO> getGamesByCategory(String category, int page, int size) {
        System.out.println("[DEBUG] GameServiceImpl.getGamesByCategory - 开始根据类别获取游戏列表，category: " + category + ", page: " + page + ", size: " + size);
        try {
            if (category == null || category.trim().isEmpty()) {
                System.err.println("[ERROR] GameServiceImpl.getGamesByCategory - 游戏类别不能为空");
                throw new RuntimeException("游戏类别不能为空");
            }
            
            int offset = (page - 1) * size;
            System.out.println("[DEBUG] GameServiceImpl.getGamesByCategory - 计算偏移量: " + offset);
            
            System.out.println("[DEBUG] GameServiceImpl.getGamesByCategory - 调用gameMapper.selectByCategory()");
            List<GameVO> gameList = gameMapper.selectByCategory(category, offset, size);
            System.out.println("[DEBUG] GameServiceImpl.getGamesByCategory - 从数据库获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            
            processGameList(gameList);
            System.out.println("[DEBUG] GameServiceImpl.getGamesByCategory - 返回游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            return gameList;
        } catch (Exception e) {
            System.err.println("[ERROR] GameServiceImpl.getGamesByCategory - 根据类别获取游戏列表失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 根据价格范围获取游戏列表
     */
    @Override
    public List<GameVO> getGamesByPriceRange(Double minPrice, Double maxPrice, int page, int size) {
        System.out.println("[DEBUG] GameServiceImpl.getGamesByPriceRange - 开始根据价格范围获取游戏列表，minPrice: " + minPrice + ", maxPrice: " + maxPrice + ", page: " + page + ", size: " + size);
        try {
            if (minPrice == null || maxPrice == null || minPrice < 0 || maxPrice < minPrice) {
                System.err.println("[ERROR] GameServiceImpl.getGamesByPriceRange - 价格范围参数错误");
                throw new RuntimeException("价格范围参数错误");
            }
            
            int offset = (page - 1) * size;
            System.out.println("[DEBUG] GameServiceImpl.getGamesByPriceRange - 计算偏移量: " + offset);
            
            System.out.println("[DEBUG] GameServiceImpl.getGamesByPriceRange - 调用gameMapper.selectByPriceRange()");
            List<GameVO> gameList = gameMapper.selectByPriceRange(minPrice, maxPrice, offset, size);
            System.out.println("[DEBUG] GameServiceImpl.getGamesByPriceRange - 从数据库获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            
            processGameList(gameList);
            System.out.println("[DEBUG] GameServiceImpl.getGamesByPriceRange - 返回游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            return gameList;
        } catch (Exception e) {
            System.err.println("[ERROR] GameServiceImpl.getGamesByPriceRange - 根据价格范围获取游戏列表失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 根据销量排序获取游戏列表
     */
    @Override
    public List<GameVO> getGamesBySalesOrder(int page, int size) {
        System.out.println("[DEBUG] GameServiceImpl.getGamesBySalesOrder - 开始根据销量排序获取游戏列表，page: " + page + ", size: " + size);
        try {
            int offset = (page - 1) * size;
            System.out.println("[DEBUG] GameServiceImpl.getGamesBySalesOrder - 计算偏移量: " + offset);
            
            System.out.println("[DEBUG] GameServiceImpl.getGamesBySalesOrder - 调用gameMapper.selectBySalesOrder()");
            List<GameVO> gameList = gameMapper.selectBySalesOrder(offset, size);
            System.out.println("[DEBUG] GameServiceImpl.getGamesBySalesOrder - 从数据库获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            
            processGameList(gameList);
            System.out.println("[DEBUG] GameServiceImpl.getGamesBySalesOrder - 返回游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            return gameList;
        } catch (Exception e) {
            System.err.println("[ERROR] GameServiceImpl.getGamesBySalesOrder - 根据销量排序获取游戏列表失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
    
    /**
     * 按类别分组获取游戏列表
     */
    @Override
    public List<GameVO> getGamesGroupedByCategory() {
        System.out.println("[DEBUG] GameServiceImpl.getGamesGroupedByCategory - 开始按类别分组获取游戏列表");
        try {
            System.out.println("[DEBUG] GameServiceImpl.getGamesGroupedByCategory - 调用gameMapper.selectGroupedByCategory()");
            List<GameVO> gameList = gameMapper.selectGroupedByCategory();
            System.out.println("[DEBUG] GameServiceImpl.getGamesGroupedByCategory - 从数据库获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            
            processGameList(gameList);
            System.out.println("[DEBUG] GameServiceImpl.getGamesGroupedByCategory - 返回游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            return gameList;
        } catch (Exception e) {
            System.err.println("[ERROR] GameServiceImpl.getGamesGroupedByCategory - 按类别分组获取游戏列表失败: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    private String getFlagValue(Integer flag) {
        System.out.println("[DEBUG] GameServiceImpl.getFlagValue - 开始处理游戏状态，flag: " + flag);
        if (flag == null) {
            System.out.println("[DEBUG] GameServiceImpl.getFlagValue - flag为空，返回空字符串");
            return BaseConstant.EMPTY;
        }

        // hard code
        String result;
        switch (flag) {
            case 1:
                result = "开发中";
                break;
            case 2:
                result = "已发布";
                break;
            case 3:
                result = "下架";
                break;
            case 4:
                result = "已删除";
                break;
            default:
                result = BaseConstant.EMPTY;
                break;
        }
        System.out.println("[DEBUG] GameServiceImpl.getFlagValue - 状态转换结果: " + result);
        return result;
    }

    /**
     * 处理游戏列表，设置状态文本值
     */
    private void processGameList(List<GameVO> gameList) {
        System.out.println("[DEBUG] GameServiceImpl.processGameList - 开始处理游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
        if (gameList != null && gameList.size() > 0) {
            gameList.forEach(game -> {
                game.setFlagValue(getFlagValue(game.getFlag()));
            });
            System.out.println("[DEBUG] GameServiceImpl.processGameList - 游戏列表处理完成");
        } else {
            System.out.println("[DEBUG] GameServiceImpl.processGameList - 游戏列表为空，跳过处理");
        }
    }
} 